﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;

namespace System.ApplicationModel
{
    public abstract partial class Entity : IDataErrorInfo
    {
        #region IDataErrorInfo
        /// <summary>
        /// Gets an error message indicating what is wrong with this object.
        /// </summary>
        [IgnoreDataMember]
        public string Error
        {
            get
            {
                ValidationContext context = new ValidationContext(this, null, null);
                ICollection<ValidationResult> errors = new List<ValidationResult>();
                if (Validator.TryValidateObject(this, context, errors, true))
                    return string.Empty;
                else
                    return string.Join(Environment.NewLine, errors.Select(e => e.ErrorMessage));
            }
        }

        /// <summary>
        /// Gets the error message for the property with the given name.
        /// </summary>
        /// <param name="columnName">The name of the property whose error message to get.</param>
        /// <returns>The error message for the property. The default is an empty string ("").</returns>
        public string this[string columnName]
        {
            get
            {
#if SILVERLIGHT
                object value = this.GetType().GetProperty(columnName).GetValue(this, null);
#else
                object value = TypeDescriptor.GetProperties(this)[columnName].GetValue(this);
#endif
                ValidationContext context = new ValidationContext(this, null, null) { MemberName = columnName };
                ICollection<ValidationResult> errors = new List<ValidationResult>();
                if (Validator.TryValidateProperty(value, context, errors))
                    return string.Empty;
                else
                    return string.Join(Environment.NewLine, errors.Select(e => e.ErrorMessage));
            }
        }
        #endregion
    }
}
